// JavaScript Document
var exercises = {};
var input = "";
var inputCorrect = null;
var maxExercises = 4;

var Exercise = Class.extend({
	arguments: [],
	answer: 0,
	min: 0,
	max: 0,
	num: 0,
	type: 0,
	name: "",
	init: function(level) {
		switch (level) {
			case 0:
				this.min = 0;
				this.max = 9;
				this.num = 1;
				this.type = 0;
				this.generateEquation();
			break
			case 1:
				this.min = 0;
				this.max = 5;
				this.num = 2;
				this.type = 1;
				this.generateEquation();
			break;
		}
	},
	generateEquation: function() {
		
		for (i = 0; i < this.num; i++) {
			this.arguments[i] = Math.ceil(Math.random() * (this.max - this.min)) + this.min;
		}
		switch (this.type) {
			case 0:
				this.answer = this.arguments[0];
				this.name = this.arguments[0].toString();
			break
			case 1:
				for (i = 0; i < this.num; i++) {
					this.answer += this.arguments[i];
					this.name += this.arguments[i].toString();
					if (i < this.num - 1) {
						this.name += " + ";
					}
				}
			break;
		}
		this.name += " = ";
	},
	getAnswer: function() {
		return this.answer;
	},
	toString: function() {
		return this.name;
	}
});

function addInput(a) {
	if (inputCorrect != null) {
		exit;
	}
	input += a;
	stringInput = input + "";
	leitud = null;
	for (k = 0; k < maxExercises; k++) {
		if (exercises[k] !== undefined) {
			stringA = exercises[k].getAnswer() + "";
			if (stringA.substr(0, stringInput.length) === stringInput) {
				leitud = k;
				if (stringA.length === stringInput.length) {
					inputCorrect = k;
					executeInput();
				}
				break;
			}
		}
	}
	if (leitud == null) {
		inputCorrect = -1;
		setTimeout(clearInput,500);
	} else {
		if (inputCorrect > -1) {
			setTimeout(clearInput,500);
		}
	}
}

function clearInput() {
	input = "";
	if (inputCorrect != null && inputCorrect > -1) {
		do {
		exercises[inputCorrect] = new Exercise(lvl);
		} while (answerOverlapping(inputCorrect));
	}
	inputCorrect = null;
}

function executeInput() {
	if (!p.isMoving()) {
		switch (inputCorrect) {
			case 0:
			p.moveY(-1);
			break;
			case 1:
			p.moveX(1);
			break;
			case 2:
			p.moveY(1);
			break;
			case 3:
			p.moveX(-1);
			break;
		}
	}
}

function answerOverlapping (n) {
	var answer = exercises[n].getAnswer();
	for (i = 0; i < maxExercises; i++) {
		if (exercises[i] !== undefined) {
			if (i != n && exercises[i].getAnswer() === answer) {
				return true;
			}
		}
	}
	return false;
}
